﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="JsonConverter.cs" company="JDML Consulting Ltd.">
//   Copyright 2011 Photon Project - http://photon.codeplex.com
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Photon.Serialization.Json
{
    using System;
    using System.IO;
    using System.Runtime.Serialization.Json;
    using System.Text;

    public class JsonConverter
    {
        private static JsonConverter _instance;

        private JsonConverter()
        {
        }

        public static JsonConverter Instance
        {
            get { return _instance ?? (_instance = new JsonConverter()); }
        }

        public T FromText<T>(string jsonText)
        {
            return (T)FromText(typeof(T), jsonText);
        }

        public object FromText(Type type, string jsonText)
        {
            using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(jsonText)))
            {
                return new DataContractJsonSerializer(type).ReadObject(stream);
            }
        }

        public string ToText(object value)
        {
            #region Validate Arguments

            Guard.ArgumentNull("value", value);

            #endregion

            using (var stream = new MemoryStream())
            {
                // serialize
                new DataContractJsonSerializer(value.GetType()).WriteObject(stream, value);
                
                // seek back to start of stream
                stream.Seek(0, SeekOrigin.Begin);
                
                // convert to text
                using (var reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    }
}
